package com.umeox.auto_light

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.umeox.logger.UMLogger

object DeviceListManager {

    /**
     * 最大支持设备
     */
    private const val MAX = 3

    /**
     * 进行中的设备数量
     */
    private var deviceProgressCount = 0

    private var allDevices = mutableListOf<DeviceProxy>()
    private var unprocessedDevices = mutableListOf<DeviceProxy>()
    private var observable = MutableLiveData(allDevices)

    val devicesObservable: LiveData<MutableList<DeviceProxy>> = observable

    fun addDevice(device: Device) {
        UMLogger.d(TAG, "添加设备 ${device.name} - ${device.mac}")
        val deviceProxy = DeviceProxy(device)
        allDevices.add(deviceProxy)
        unprocessedDevices.add(deviceProxy)
        startDeviceTaskIfNeed()
    }

    private fun startDeviceTaskIfNeed() {
        if (deviceProgressCount < MAX) {
            unprocessedDevices.removeFirstOrNull()?.let {
                deviceProgressCount++
                it.startTask()
                notifyStatusChange()
            }
        }
    }

    fun finishDeviceTaskAndStartNextIfNeed() {
        notifyStatusChange()
        deviceProgressCount--
        startDeviceTaskIfNeed()
    }

    fun startTask() {
        UMLogger.d(TAG, "开始自动检测全亮屏任务")
        DeviceSearchManager.startScanTask()
    }

    private fun notifyStatusChange() {
        observable.postValue(allDevices)
    }
}